import React, { Component } from 'react'
import Styled from 'styled-components'
import ValidProjectName from 'graphql/org/ValidProjectName.graphql'
import NewProject from 'graphql/org/newProject.graphql'
import { ValidType } from 'components/validForm'
import {
  Form as FormTable, Section as TableSection, Input, Submit,
} from 'components/tableForm'

const getVariables = values => ({
  description: values.description.value,
  name: values.name.value,
})

const StyledContent = Styled.div`
  padding-top: 30px;
  overflow: scroll; 
  height: 100%;
  padding-left: 30px;
  padding-right: 30px;
  width:100%;
`

export default class newDataset extends Component {
  componentDidMount = () => {}

  render() {
    const { org } = this.props
    const orgName = org.owner_object.name
    const orgId = org.owner_object.id
    const nameRule = [
      {
        type: ValidType.REGULAR,
        value: /^[\s\S]*.*[^\s][\s\S]*$/,
        errorMessage: '项目名称不能为空',
      },
      {
        type: ValidType.REGULAR,
        value: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
        errorMessage: '项目名称由中文、英文数字包括下划线',
      },
      {
        type: ValidType.REMOTE,
        value: {
          query: ValidProjectName,
          params: { ownerId: orgId },
        },
        errorMessage: '该项目已经存在于你的账户',
        getResult: re => re.project.length === 0,
      },
    ]
    const descriptionRule = [
      {
        type: ValidType.MAXLENGTH,
        value: 1000,
        errorMessage: '项目名称长度不超过1000个字符',
      },
    ]
    return (
      <StyledContent>
        <FormTable>
          <TableSection header="新建项目">
            <Input
              name="name"
              header="项目名称"
              description="项目名称可包含 字母、数字、中划线。"
              rules={nameRule}
            />
            <Input
              nullable
              initValue=""
              name="description"
              header="项目说明"
              description="项目说明由 0 ~ 1000 个字符组成."
              rules={descriptionRule}
              textArea
            />
          </TableSection>
          <Submit
            submit={{
              text: '提交',
              variables: { ownerId: orgId },
              getVariables,
              mutation: NewProject,
              success: (data) => {
                if (data && data.insert_project && data.insert_project.returning) {
                  return `/project/${orgName}/${data.insert_project.returning[0].name}`
                }
                return '/project'
              },
            }}
            cancle={{ text: '取消', url: `/org/${orgName}/project` }}
            redirect
          />
        </FormTable>
      </StyledContent>
    )
  }
}
